# %%
import os
import pandas as pd  # type: ignore
import warnings

warnings.simplefilter(action='ignore', category=FutureWarning)

# Dataframe设置不显示小数点
pd.set_option('display.precision', 0)

File_Path = os.path.join(os.path.expanduser("~"), 'Desktop') + "\\每日动环\\3.0"
# 定义地点和等级的期望顺序
df_index = ['一级', '二级', '三级', '四级']
levels_order = ['一级告警', '二级告警', '三级告警', '四级告警']

locations_order = [
    '广州', '深圳', '东莞', '佛山', '中山', '惠州', '珠海', '江门', '汕头', '湛江', '揭阳', '肇庆',
    '韶关', '清远', '茂名', '梅州', '潮州', '阳江', '河源', '汕尾', '云浮', '科学城', '松山湖', '白云北',
    '知识城'
]
alarm = {'重要告警': '二级', '普通告警': '三级', '紧急告警': '一级', '一般告警': '四级'}
Local_City = {}
SC = res_zvn = region_out = kfs_out = gateway = 0


# %%
def znv(res_zvn):
    global locations_order, df_index, region_out
    # 监控中心归类地市
    res_zvn['监控中心'] = res_zvn['监控中心'].str[:2]
    res_zvn = res_zvn[~res_zvn['监控中心'].isin(['佛山', '湛江', '梅州', '河源', '汕尾'])]

    # 统计告警等级数据
    result = res_zvn.groupby(['监控中心', '告警级别']).size().unstack(fill_value=0)
    if type(region_out) != int:
        result = pd.concat([result, region_out])
    # 将NAN空值设为0
    result.fillna(0, inplace=True)
    # 重新排序，按指定顺序排序行列
    output = result.reindex(index=locations_order, columns=df_index)
    for i in ['惠州', '揭阳', '梅州', '潮州', '韶关', '白云北', '知识城']:
        output.loc[i] = '/'

    return output


def kfs(path, name):
    global df_index
    df = pd.read_excel(path, header=0)
    kfs = df['级别 (level)'].value_counts().to_dict()
    kfs = pd.DataFrame(kfs, index=[name.split('.')[0]])
    out = pd.DataFrame(kfs).reindex(columns=df_index)
    # 将NAN空值设为0
    out.fillna(0, inplace=True)
    return out


def Shenzhen(path, name):
    global locations_order, df_index, alarm
    Local_City = {}
    df = pd.read_excel(path, header=6)
    df['告警级别'] = df['告警级别'].map(alarm)
    Local_City[name.split('.')[0]] = dict(df['告警级别'].value_counts())
    out = pd.DataFrame(Local_City).T.reindex(columns=df_index)
    # 将NAN空值设为0
    out.fillna(0, inplace=True)
    return out


def vertiv(SC):
    global locations_order, levels_order, df_index, alarm
    # 定义地点映射字典
    location_map = {
        '广州联通': '广州',
        '江门联通维谛动环监控系统': '江门',
        '佛山联通': '佛山',
        '肇庆联通': '肇庆',
        '中山联通动环监控': '中山',
        '湛江联通': '湛江',
        '汕头联通': '汕头',
        '中国联通华南（东莞）数据中心二期': '松山湖',
        '惠州联通动环监控系统': '惠州',
        '珠海联通监控中心': '珠海',
        '韶关联通': '韶关',
        '广州白云联通IDC': '白云北',
        '东莞联通监控中心': '东莞',
        '揭阳联通动环监控': '揭阳',
        '梅州联通动环监控': '梅州',
        '潮州联通监控中心': '潮州',
        '广州联通知识城': '知识城',
        '阳江联通IDC机房': '阳江',
        '汕尾联通': '汕尾',
        '清远联通': '清远'
    }

    # 使用map函数进行地点名称的映射
    SC['监控中心'] = SC['监控中心'].map(location_map)

    # 使用groupby进行统计
    result = SC.groupby(['监控中心', '事件等级']).size().unstack(fill_value=0)

    # 根据定义的顺序重排DataFrame的行和列
    output = result.reindex(index=locations_order, columns=levels_order)
    # 将NAN空值设为0
    output.fillna(0, inplace=True)
    # 对于没有数据的监控中心，填充为/
    for i in ['深圳', '东莞', '佛山', '中山', '茂名', '河源', '云浮', '科学城']:
        output.loc[i] = '/'
    return output


def history(new_path):
    '''3.0'''
    df = pd.read_excel(new_path, header=0)
    gateway = df['所属计算节点 (gateway)'].value_counts().to_dict()
    gateway['科学城DCIM北向'] = gateway.pop('广州科学城DCIM北向')
    gateway['白云北维谛'] = gateway.pop('广州白云北维谛')
    gateway['知识城维谛'] = gateway.pop('广州知识城维谛')
    gateway['松山湖C'] = gateway.pop('东莞松山湖北向')
    C = {}
    api = {}
    for i in gateway:
        if 'C' in i:
            if i[:2] in C:
                C[i[:2]] = gateway[i] + C[i[:2]]
            else:
                C[i[:2]] = gateway[i]
        elif '维谛' in i:
            api[i[:2]] = gateway[i]
    locations_order = [
        '广州', '深圳', '东莞', '佛山', '中山', '惠州', '珠海', '江门', '汕头', '湛江', '揭阳', '肇庆',
        '韶关', '清远', '茂名', '梅州', '潮州', '阳江', '河源', '汕尾', '云浮', '科学', '松山', '白云',
        '知识'
    ]
    gateway_C = pd.DataFrame(C, index=['C接口']).T.reindex(index=locations_order)
    gateway_api = pd.DataFrame(api,
                               index=['API']).T.reindex(index=locations_order)
    gateway = pd.concat([gateway_C, gateway_api], axis=1)

    gateway.fillna('/', inplace=True)
    gateway = gateway.rename(index={
        '科学': '科学城',
        '松山': '松山湖',
        '白云': '白云北',
        '知识': '知识城'
    })
    return gateway


# %%
def match_ss(name, path):
    global res_zvn, SC, gateway, region_out, kfs_out, File_Path, Local_City, ont_zvn, res_vert
    match name:
        case x if 'devicealarmdetail' in x:
            if type(res_zvn) == int:
                res_zvn = pd.read_excel(path, header=6)
            else:
                res_zvn = pd.concat(
                    [res_zvn, pd.read_excel(path, header=6)],
                    ignore_index=True)
        case x if 'SC' in x:
            print(f'数据为空时,一定要打开{name}并保存一下。')
            if type(SC) == int:
                SC = pd.read_excel(path)
            else:
                SC = pd.concat([SC, pd.read_excel(path)], ignore_index=True)
        case x if '历史' in x:
            gateway = history(path)
        case _:
            region_unction(name, path)


def region_unction(name, path):
    global region_out, kfs_out, Local_City, res_zvn, SC, gateway, File_Path, ont_zvn, res_vert
    match name:
        case x if x[:2] in ['科学', '佛山', '松山']:
            if type(kfs_out) == int:
                kfs_out = kfs(path, name)
            else:
                kfs_out = pd.concat([kfs_out, kfs(path, name)])
        case x if '深圳' in x:
            if type(kfs_out) == int:
                kfs_out = Shenzhen(path, name)
            else:
                kfs_out = pd.concat([kfs_out, Shenzhen(path, name)])
        case _:
            df = pd.read_excel(path, header=6)
            Local_City[name.split('.')[0]] = dict(df['告警级别'].value_counts())
            region_out = pd.DataFrame(Local_City).T.reindex(columns=df_index)


# %%
def main():
    global File_Path, names, Local_City, SC, res_zvn, region_out, kfs_out, gateway, ont_zvn, res_vert
    File_Path = os.path.join(os.path.expanduser("~"),
                             'Desktop') + "\\每日动环\\3.0"
    names = os.listdir(File_Path)
    for name in names:
        path = os.path.join(File_Path, name)
        match_ss(name, path)

    ont_zvn = znv(res_zvn)
    if type(kfs_out) != int:
        for i in kfs_out.index:
            ont_zvn.loc[i] = kfs_out.loc[i]
    ont_zvn['力维总量'] = ont_zvn.sum(axis=1, skipna=True)
    res_vert = vertiv(SC)
    res_vert['维谛总量'] = res_vert.sum(axis=1, skipna=True)
    output = pd.concat([ont_zvn, res_vert, gateway], axis=1)

    return output


# %%
if __name__ == '__main__':
    aa = main()
    print(aa)
    # aa.to_excel(os.path.join(os.path.expanduser("~"), 'Desktop') +'\\ss.xlsx',index=True,header=True)
